package de.hmm.hwip.connection.client;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.osgi.framework.BundleContext;

import android.util.Log;

import de.hmm.hwip.connection.api.IConIn;

/**
 * OSGi Gateway network service
 * Listen on Socket, wait for connection
 * 
 * @author johannes mendel
 * @version 24.10.2012
 *
 */
public class GatewayServer implements Runnable{
	/**
	 * Class identifier to debug
	 */
	final private String TAG = "Gateway Server (connection client)";
	
	/**
	 * Gateway server socket - is listening for connection
	 */
	private ServerSocket gatewayServer;
	
	/**
	 * Gateway port where connection can enter the system
	 */
	private static int gwPort = 7600;
	
	/**
	 * used socket
	 */
	private Socket client;
	
	/**
	 * network osgi service Interface
	 */
	private IConIn service = null;
	
	/**
	 * OSGi bundlecontext
	 */
	private BundleContext context;
	
	/**
	 * identifier if Server is open or closed
	 */
	private static boolean open = true;
	
	/**
	 * Class constructor
	 * @param service -> OSGi Service for incoming connections
	 * @param context -> OSGi bundlecontext
	 */
	public GatewayServer(IConIn service, BundleContext context){
		this.service = service;
		this.context = context;
	}
	
	@Override
	public void run() {
		try 
		{
			// generate new server socket
			gatewayServer = new ServerSocket(gwPort);
			
			while(open) 
			{
				Log.i(TAG, "Listen on port: " + gwPort + "...");
				// accept the connect ...
				client = gatewayServer.accept();
				
				// ... and start the network service thread
				service.startCon(client, context);
			}
			client.close();
			gatewayServer.close();
		}
	    catch(Exception e) 
	    {
	    	Log.e(TAG, "Exception: " + e.getMessage());
	    }
		
		closeSocket();
	}
	
	/** closes socket **/
	private void closeSocket()
	{
		try {
			gatewayServer.close();
		} catch (IOException e) {
			Log.e(TAG, "unable to close Gateway socket");
		}
	}
	
	/**
	 * Method to close the Server
	 */
	public static void closeGateway(){
		open = false;
	}

}
